#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pylibmc
import urllib2
import sys
import redisClient
import hashlib
import time,datetime
from string import Template
import settings

_server = settings.web_server
_urls = [
        Template('/client/newmainvideo?staDate=${staDate}&pd=${pd}&items=UV,VV,NU,VVUV,Comp,CompVV,'),
        Template('/client/newmainpaike?staDate=${staDate}&pd=${pd}&items=UV,VV,NU,VVUV,NR,SU,FU,'),
        Template('/client/channelday?staDate=${staDate}&pd=${pd}'),
        Template('/client/citydaypaike?staDate=${staDate}&pd=${pd}'),
        Template('/client/citydayvideo_copy?staDate=${staDate}&pd=${pd}'),
    ]
_pd = (7, 30, 90)

def CacheInital():
    CleanCache()
    
    for url in _urls:
        for pd in _pd:
            
            a = datetime.datetime.today()
            b = a + datetime.timedelta(-pd)
            staDate = b.strftime('%Y/%m/%d')
            
            urlstr = url.substitute(staDate=staDate, pd=pd)
            try:
                path = '{0}{1}'
                path = path.format(_server,urlstr)
                print path
                content = urllib2.urlopen(path, timeout=2000).read()
            except:
                print 'HTTPError:{0}{1}'.format(_server,key)
    

def CacheManage():
    rc = redisClient.client()
    mc = pylibmc.Client(settings.mem_cache_server, binary=True)
    keys = rc.hgetall('weburlcachekey')
    keylist = keys.get('keys','[]')
    keylist = eval(keylist)
    newkeylist = []
    for key in keylist:
        print key
        md5key = hashlib.md5(key).hexdigest()
        content = mc.get(md5key)
        
        if not content:
            continue
        else:
	        mc.delete(md5key)
        
        if not key.startswith('/'):
            continue
        
        try:
            path = '{0}{1}'
            path = path.format(_server,key)
            content = urllib2.urlopen(path, timeout=2000).read()
            #mc.set(key,content)
            newkeylist.append(key)
        except:
            print 'HTTPError:{0}{1}'.format(_server,key)
    
    rc.hset('weburlcachekey','keys', newkeylist)
    
        
def CleanCache():
    rc = redisClient.client()
    mc = pylibmc.Client(settings.mem_cache_server, binary=True)
    keys = rc.hgetall('weburlcachekey')
    keylist = keys.get('keys','[]')
    keylist = eval(keylist)
    for key in keylist:
        print key
        md5key = hashlib.md5(key).hexdigest()
        content = mc.get(md5key)
        
        if not content:
            pass
        else:
	        mc.delete(md5key)
        
    rc.hset('weburlcachekey','keys', [])
    
    
	
if __name__ == '__main__':
    cmd = ''
    if len(sys.argv) == 2:
        cmd = sys.argv[1]

    if cmd == 'update':
        print "CacheManage()"
        CacheManage()
    elif cmd == 'clean':
        print "CacheClean()"
        CleanCache()
    elif cmd == 'init':
        print "CacheInital()"
        CacheInital()
    else:
        print "Nothing Happen!"
